package com.xhwl.centiotdata.suppliersystem.daguan;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.dto.dahua.DeviceDaGuanDTO;
import com.xhwl.centiotdata.pojo.dto.device.DeviceIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.dto.haikanginfo.InfoIntegrationPropertiesDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tangwei
 * @description 拉取达观信息发布屏设备
 * @create 2023-10-27 10:50
 */
@Slf4j
@Service
public class DeviceDaGuanHandler {

    /**
     * 拉取达观信息发布设备，不需要过ROMA
     * 达观子系统配置了白名单，不需要鉴权
     *
     * @param configDTO 集成配置
     * @return result
     */
    public List<DeviceDaGuanDTO> pullDevice(InfoIntegrationPropertiesDTO configDTO) {

        String result = HttpUtil.get(configDTO.getIpAndPort() + "/openapi/v1/terminal");
        log.info("获取的达观设备请求结果==>{}", result);
        JSONObject jsonObject = JSON.parseObject(result);
        if (jsonObject.getIntValue("code") != 0) {
            return new ArrayList<>();
        }
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        if (CollectionUtils.isEmpty(jsonArray)) {
            return new ArrayList<>();
        }
        List<DeviceDaGuanDTO> deviceList = new ArrayList<>(jsonArray.size());
        int onlineStatus = 1;
        jsonArray.forEach(json -> {
            JSONObject item = (JSONObject) json;
            DeviceDaGuanDTO deviceDaGuanDTO = DeviceDaGuanDTO.builder()
                    .deviceName(item.getString("terminalName"))
                    .deviceCode(item.getString("sn"))
                    .isOnline(item.getIntValue("online") == onlineStatus).build();
            deviceList.add(deviceDaGuanDTO);
        });
        return deviceList;

    }
}
